package com.atguigu.core.util;

import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;

import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import static java.util.regex.Pattern.compile;

/**
 * MessageParseUtil
 *
 * @author Navi
 */
public class MessageParseUtils {
  static Pattern p = Pattern.compile("(\\$\\{)([\\w]+)(\\})");
  static final String MESSAGE_KEY_REG = ".*\\{\\w.+\\}.*";
  static final String MESSAGE_REG = ".*\\{\\}.*";

  public static String messageParse(String content, Map<String, String> kvs) {
    Matcher m = p.matcher(content);
    StringBuffer sr = new StringBuffer();
    while (m.find()) {
      String group = m.group();
      m.appendReplacement(sr, kvs.get(group));
    }
    m.appendTail(sr);
    return sr.toString();
  }

  /**
   * 提醒消息内容{} 替换
   *
   * @param messageText
   * @param params
   * @return
   */
  public static String replaceTemplateMessage(String messageText, String... params) {
    if (!messageText.matches(MESSAGE_REG)) {
      return messageText;
    }
    if (ObjectUtil.isNull(params)) {
      return messageText;
    }
    StringBuffer rtnSb = new StringBuffer();
    Pattern pattern = compile("(?<msgInfo>.*?\\{}[^\\{]*)");
    Matcher matcher = pattern.matcher(messageText);
    int msgCount = 0;
    while (matcher.find()) {
      String msgPara = "";
      while (StrUtil.isBlank(msgPara)) {
        if (msgCount <= params.length - 1) {
          msgPara = params[msgCount];
        } else {
          break;
        }
        msgCount++;
      }
      rtnSb.append(matcher.group("msgInfo").replaceAll("\\{\\}", msgPara));
    }
    return rtnSb.toString();
  }
}
